<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <metaname="viewport"content="initial-scale=1.0, user-scalable=no, width=device-width"/>
    <style>
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
      }

      .input-box {
        position: fixed;
        top: 100px;
        left: 50px;
        z-index: 9999;
      }

      .toast {
        width: 260px;
        height: 160px;
        padding: 20px;
        position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 9999;
        background-color: #fff;
        border-radius: 10px;
      }

      .botton-box {
      }

      .botton {
        width: 100px;
        border: none;
        color: #fff;
        border-radius: 6px;
        height: 30px;
        line-height: 30px;
      }

      .hide {
        display: none;
      }
    </style>
    <title>划分区域</title>
    <link
      rel="stylesheet"
      href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"
    />
    <link
      rel="stylesheet"
      href="https://cache.amap.com/lbs/static/main1119.css"
    />
    <script type="text/javascript">
      window._AMapSecurityConfig = {
        securityJsCode: "72df03a4f5c81fe654237421e329f058",
      };
    </script>
    <script
      type="text/javascript"
      src="https://www.njshenb.cn/vendor/laravel-admin/AdminLTE/plugins/jQuery/jQuery-2.1.4.min.js"
    ></script>
    <script src="https://webapi.amap.com/maps?v=2.0&key=46c54750ab83b42a84c4e661546e03a6&plugin=AMap.PolygonEditor,AMap.AutoComplete,AMap.PlaceSearch"></script>
    <script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
    <script
      type="text/javascript"
      src="https://cache.amap.com/lbs/static/addToolbar.js"
    ></script>
  </head>

  <body>
    <div id="container" style="width:100%;height:1000px;"></div>

    <div class="info" style="margin-top:100px">
      <div class="input-item">
        <div class="input-item-prepend">
          <span class="input-item-text" style="width: 8rem">请输入关键字</span>
        </div>
        <input id="tipinput" type="text" />
      </div>
    </div>

    <div class="input-card" style="width: 120px">
      <button class="btn" onclick="createPolygon()" style="margin-bottom: 5px">
        新建区域
      </button>
      <!-- <button
        class="btn"
        onclick="polyEditor.open()"
        style="margin-bottom: 5px"
      >
        开始编辑
      </button> -->
      <!-- <button
        class="btn"
        onclick="polyEditor.close()"
        style="margin-bottom: 5px"
      >
        结束编辑
      </button> -->
      <button class="btn" onclick="remove()">删除区域</button>
    </div>

    <!-- 弹窗 -->
    <div class="toast">
      <div style="margin-bottom: 20px; font-size: 15px">设置网点</div>
      <select id="sid" onchange="selectcity()">
        <option value="">=====请选择====</option>
      </select>
      <div
        style="
          margin-top: 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        "
      >
        <button
          onclick="confirm()"
          class="botton"
          style="background-color: dodgerblue"
        >
          确认
        </button>

        <button
          onclick="colse()"
          class="botton"
          style="background-color: #f3f3f3; color: #999"
        >
          取消
        </button>
      </div>
    </div>
    <script type="text/javascript">
      var overlays;
      var polyEditor;
      var map;
      var points_id;
      var dataArr = [];
      var polygonArr = [];

      var textStyle = {
        fontSize: 12,
        fontWeight: "normal",
        fillColor: "#fff",
        // fillColor: 'rgb(255, 215, 0)',
        // strokeColor: '#fff',
        // strokeWidth: 2,
        // fold: true,
        // padding: "30",
        backgroundColor: "rgb(246,137,38)",
        borderColor: "#fff",
        // borderWidth: 1,
      };

      var formData = {
        points: "", //经纬度
        admin_id: "", //网点id
        points_data: "", //经纬度数据
        points_id: "", //区域id
      };

      //初始化隐藏弹窗
      $(".toast").hide();
      getAllPoints();
      getMerchant();

      $(function () {
        map = new AMap.Map("container", {
          center: [114.31557, 30.59743],
          zoom: 10,
        });

        //输入提示
        var auto = new AMap.AutoComplete({
          input: "tipinput",
        });
        var placeSearch = new AMap.PlaceSearch({
          map: map,
        }); //构造地点查询类
        auto.on("select", select); //注册监听，当选中某条记录时会触发
        function select(e) {
          placeSearch.setCity(e.poi.adcode);
          placeSearch.search(e.poi.name); //关键字查询查询
        }

        //标注
        var markers = [];
        var layer = new AMap.LabelsLayer({
          zooms: [3, 20],
          zIndex: 1000,
          collision: false,
          allowCollision: false,
        });
        layer.add(markers);
        map.add(layer); // 图层添加到地图

        dataArr.map((e) => {
          if (e.points_data) {
            var latlon = jQuery.parseJSON(e.points_data);
            polygonArr.push(
              new AMap.Polygon({
                path: latlon,
              })
            );

            var marker = new AMap.LabelMarker({
              name: e.name,
              position: latlon[0],
              zIndex: 9999,
              text: {
                content: e.name,
                direction: "center",
                style: textStyle,
              },
            });
            markers.push(marker);
          }
        });

        layer.add(markers);

        map.add(polygonArr);
        map.setFitView();
        polyEditor = new AMap.PolygonEditor(map);
        polyEditor.addAdsorbPolygons(polygonArr);

        //操作划分区域

        polyEditor.on("add", function (data) {
          // var polygonItem = data.obj;
          // var path = polygonItem.getPath(); //取得绘制的多边形的每一个点坐标
          var polygon = data.target;
          overlays = polygon;

          polyEditor.addAdsorbPolygons(polygon);

          //区域划分右键事件，可以唤出弹窗选择网点
          polygon.on("rightclick", (e) => {
            var polygonItem = data.target;
            var path = polygonItem.getPath(); //取得绘制的多边形的每一个点坐标
            formatPoints(path);
            console.log(path);
            polyEditor.close();
            overlays = e.target;
            $(".toast").show();
            // map.remove(overlays);
          });

          //区域划分完以后点击完成
          polygon.on("click", (e) => {
            overlays = e.target;
            polyEditor.setTarget(polygon);
            polyEditor.open(); //开始编辑
            // polygonAttr = polygon;
            // openInfo(e.lnglat, n);
          });
        });

        //遍历所有区域事件
        polygonArr.map((obj, k) => {
          polygonArr[k].on("click", (e) => {
            overlays = e.target;
            polyEditor.setTarget(polygonArr[k]);
            polyEditor.open();
            points_id = dataArr[k].points_id;
            // openInfo(e.lnglat, dataArr[k]);
          });

          //区域划分右键事件，可以唤出弹窗选择网点
          polygonArr[k].on("rightclick", (e) => {
            formData.points_id = dataArr[k].points_id;
            $("#sid").val(dataArr[k].id);
            formData.admin_id = dataArr[k].id;
            var polygonItem = e.target;
            var path = polygonItem.getPath(); //取得绘制的多边形的每一个点坐标
            formatPoints(path);
            console.log(path);
            polyEditor.close();
            overlays = e.target;
            $(".toast").show();
            // map.remove(overlays);
          });
        });
      });

      //关闭设置区域弹窗
      function colse() {
        $(".toast").hide();
      }

      //计算中心点
      function mapGetCenter(pointArray) {
        var sortedLongitudeArray = pointArray.map((item) => item[1]).sort(); //首先对经度进行排序，红色部分是array中经度的名称
        var sortedLatitudeArray = pointArray.map((item) => item[0]).sort(); //对纬度进行排序，红色部分是array中纬度的名称
        var centerLongitude = (
          (parseFloat(sortedLongitudeArray[0]) +
            parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) /
          2
        ).toFixed(6);
        const centerLatitude = (
          (parseFloat(sortedLatitudeArray[0]) +
            parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) /
          2
        ).toFixed(6);

        //如果经纬度在array中不是数字类型，需要转化为数字类型进行计算，如果是可以去掉parseFloat处理
        //console.log(centerLongitude+"kkk"+centerLatitude);
        return [parseFloat(centerLongitude), parseFloat(centerLatitude)];
      }

      //获取区域
      function getAllPoints() {
        $.ajax({
          url: "https://www.njshenb.cn/api/merchant/admin_points/listing",
          type: "post",
          dataType: "json",
          data: {},
          async: false,
          success: function (res) {
            dataArr = res.data;
          },
        });
      }

      //删除划分区域
      function remove() {
        if (!points_id) {
          alert("请框选区域");
          return;
        }

        polyEditor.close();
        map.remove(overlays);
        removePolygon();
      }

      //新建划分区域
      function createPolygon() {
        formData.points_id = "";
        polyEditor.close();
        polyEditor.setTarget();
        polyEditor.open();
      }

      //下拉获取网点
      function selectcity() {
        let sid = $("#sid").val();
        formData.admin_id = sid;
      }

      //格式化数据
      function formatPoints(datalist) {
        var points_data = [];
        var points = [];
        datalist.map((e) => {
          points_data.push([e.lng, e.lat]);

          let obj = {
            lng: e.pos[0],
            lat: e.pos[1],
            latLng: {
              lng: e.lng,
              lat: e.lat,
            },
          };
          points.push(obj);
        });

        let obj1 = JSON.stringify(points_data);
        let obj2 = JSON.stringify(points);

        formData.points_data = obj1;
        formData.points = obj2;
      }

      //获取区域数据
      function getMerchant() {
        $.ajax({
          url: "https://www.njshenb.cn/api/merchant/merchant/listing",
          type: "post",
          dataType: "json",
          data: {},
          success: function (res) {
            var str = "";
            for (var i = 0; i < res.data.length; i++) {
              str +=
                "<option  value = '" +
                res.data[i].id +
                "'>" +
                res.data[i].name +
                "</option>"; //拼接option
            }
            $("#sid").append(str);
          },
        });
      }

      //校验
      function confirm() {
        $(".toast").hide();

        if (formData.admin_id == "") {
          alert("请选择网点");
          return;
        }

        if (formData.points == "") {
          alert("请框选区域");
          return;
        }
        addPoints();
      }

      //添加区域
      function addPoints() {
        $.ajax({
          url: "https://www.njshenb.cn/api/merchant/admin_points",
          type: "post",
          dataType: "json",
          data: formData,
          success: function (res) {
            alert(res.msg);
          },
        });
      }

      //删除区域
      function removePolygon() {
        $.ajax({
          url: "https://www.njshenb.cn/api/merchant/admin_points/del",
          type: "post",
          dataType: "json",
          data: {
            points_id: points_id,
          },
          success: function (res) {
            alert(res.msg);
          },
        });
      }

      //提示信息
      function openInfo(p, obj) {
        //构建信息窗体中显示的内容
        var info = [];
        // info.push("<div><div><img style=\"float:left;\" src=\" http://webapi.amap.com/images/autonavi.png \"/></div> ");
        info.push(
          `<div style=\"padding:0px 0px 0px 4px;margin-top:10px\"><b>网点名称：${obj.name}</b>`
        );
        infoWindow = new AMap.InfoWindow({
          content: info, //使用默认信息窗体框样式，显示信息内容
        });
        infoWindow.open(map, p);
      }
    </script>
  </body>
</html>
